package br.com.perkins.myproject.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import br.com.perkins.myproject.domain.Menu;
import br.com.perkins.myproject.persistence.DaoGenerico;
import br.com.perkins.myproject.service.exception.ServiceException;

/**
 * MenuService
 * bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla
 * bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla
 * @ServiceExceptions: #101 - #130
 */

@Service("menuService")
@Scope("prototype")
public class MenuServiceImpl extends ServiceImpl implements MenuService {

	@Resource
	private DaoGenerico <Menu,Integer> menuDao;

	@Override
	public Menu validar(Menu menu) {
		boolean valid = true;

		if (menu == null) {
			this.newServiceException(101);
		}
		if ((menu.getNome() == null) || (menu.getNome().isEmpty())) {
			this.newServiceException(102);
		}
		return menu;
	}

	@Override
	public Menu salvar(Menu menu) {
		try {
			menu = menuDao.salvar(this.validar(menu));
			checkForServiceException();
		} catch (ServiceException serviceException) {
			throw serviceException;
		} catch(Exception exception) {
			this.newServiceException(101);
			checkForServiceException();
		}
		return menu;
	}

	@Override
	public Menu pesquisar(Menu menu) {
		try {
			menu = menuDao.pesquisarPorId(menu.getId());
		} catch(Exception exception) {
			this.newServiceException(102);
			checkForServiceException();
		}
		return menu;
	}

	@Override
	public Menu atualizar(Menu menu) {
		try {
			menu = menuDao.atualizar(this.validar(menu));
		}
		catch (ServiceException serviceException) {
			throw serviceException;
		} catch(Exception exception) {
			this.newServiceException(103);
			checkForServiceException();
		}
		return menu;
	}

	@Override
	public void excluir(Menu menu) {
		try {
			menuDao.excluir(menu);
		} catch(Exception exception) {
			this.newServiceException(131);
			checkForServiceException();
		}
	}

	@Override
	public List<Menu> todos() {
		List<Menu> menus = null;
		try {
			menus = menuDao.todos();
		} catch(Exception exception) {
			this.newServiceException(002);
			checkForServiceException();
		}
		return menus;
	}

	@Override
	public List<Menu> getPesqNome(String pesquisa) {
		List<Menu> menus = null;

		Map<String, Object> params = new HashMap<String,Object>();
		params.put("nome", "%"+ pesquisa + "%");

    	String query="SELECT m FROM Menu m WHERE m.nome " +
    					"LIKE :nome";

    	try {
			menus = menuDao.listPesqParam(query, params);
		} catch(Exception exception) {
			this.newServiceException(003);
			checkForServiceException();
		}
		return menus;
	}

}